<?php
/**
 * @name UsersController.php
 * @copyright (c) 2011
 * @author Arsene Tochemey GANDOTE<arsene.gandote@yahoo.com>
 */
class UsersController extends AppController {

	var $name = 'Users';

	# Controller Actions
    
    function  beforeFilter() {
          parent::setUpGlobalConfig();
   }
    
	/**
	 * This function sets the user session data that will be used through out the runnning of the application.
	 * @name _setUserSession
	 * @param mixed $sessionData array containing the user session data.
	 * @return void
	 * @access public
	 */
	function __setUserSession($sessionData){
		# set the user session data
		$this->Session->write('userSessionData', $sessionData);
	}

	/**
	 * This function checks the login credentials of the user.
	 * @name login
	 * @var string $loginName
	 * @var string $loginKey
	 * @return Json Data
	 * @access public
	 */
	function login(){
		# array containing the user credential data
		$userCredentialData = array();
		# check whether the HTTP Request is an ajax request
		if($this->request->is('ajax')){
			# disable the rendering of the layout
			$this->autoRender = false;
			$this->autoLayout = false;

			# store the login name and password
			$logingName = $_POST['username'];
			$loginKey = $_POST['password'];

			# Hash the password entered by the user
			# The below line of code will be commented when the application is live.
			 $loginKeyHashed =md5($loginKey);

			# set the data to validate for the model User
			$this->request->data['User'] = array(
			'username' => $logingName,
			'password' => $loginKey
			);
			$this->User->set($this->request->data);

			# check the username and password tally with the validation rules
			if($this->User->validates(array('fieldList' => array('username', 'password')))){
				# verify whether the user is in the database or not
				$userCredentialData = $this->User->getUserByLoginName($logingName);
                
				# check whether the user exists in the system or not.
				//if($this->User->getNumRows() != 0){
                if($userCredentialData){
					# Check whether the user is enabled
					$userStatus = $userCredentialData['User']['status'];

					if($userStatus == 1){
						# Check whether the password tallies with the one in the system
						if(strcmp($loginKeyHashed, $userCredentialData['User']['password']) == 0){
							# return the user credential array data
							$this->__setUserSession($userCredentialData['User']);
							return json_encode(array('code' => 0, 'mesg' => 'Credentials Verified'));
						}
						else{
							$errors = array('code' => 1, 'mesg' => 'Invalid login Credentials');
							return json_encode($errors);
						}
					}
					else{
						$errors = array('code' => 1, 'mesg' => 'Your Account is Disabled');
						return json_encode($errors);
					}
				}
				else{
					$errors = array('code' => 1, 'mesg' => 'Invalid login Credentials');
					return json_encode($errors);
				}
			}
			else{
				$errors = array('code' => 2, 'mesg' =>$this->User->invalidFields());
				return json_encode($errors);
			}
		}
	}

	/**
	 *This function initialises the user. It allows the user to use the application
	 * @name initLogin
	 * @return Json data
	 * @access public
	 */
	function initLogin(){
		# check whether the HTTP Request is an ajax request
		if($this->request->is('ajax')){
			# disable the rendering of the layout
			$this->autoRender = false;
			$this->autoLayout = false;
			# check the user login
			return $this->login();
		}
	}

	/**
	 * This function logs out the user from the application. It deletes the user session data
	 * @name logout
	 * @return void
	 * @access public
	 */
	function logout(){
		# Delete the user session data
		$this->Session->delete('userSessionData');
        $this->Session->destroy('recentMembersUsed');
		# Rediect the user to the login page
		$this->redirect('/');
	}

	/**
	 * This function redirects the user to his appropriate page based upon his role
	 * @name signIn
	 * @param void
	 * @return void
	 * @access public
	 */
	function signIn(){
		# disable the rendering of the layout
		$this->autoRender = false;
		$this->autoLayout = false;

		# Check the user validity
		if($this->Session->check('userSessionData')){
			$this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
		}
		else{
			$this->redirect('/');
		}
	}

	/**
	 * This function update the user account Settings
	 * @name passwordChecks
	 * @param string $password_1
	 * @param string $password_2
	 * @param string $currentPassword
	 * @param string $oldPassword
	 * @return True or false or an array of errors message
	 * @access public
	 */
	function passwordChecks($password_1, $password_2, $currentPassword, $oldPassword){
		# Array containing the return data.
		$returnData = array();
		# Get the old Password provided by the user
		$currentPassword = md5($currentPassword);
		# Check whether the password provided by the user matches his old password
		if(strcmp($currentPassword, $oldPassword) != 0){
			$returnData['code'] = 3;
			$returnData['mesg'] ='Wrong Old Password Provided';
		}
		else{ # Check whether the new supplied passwords match
			if(strcmp($password_1, $password_2) != 0){
				$returnData['code'] = 4;
				$returnData['mesg'] ='Password do not match';
			}
			else{
				#Password Check Success
				$returnData['code'] = 0;
				$returnData['mesg'] ='Success';
			}
		}
		return $returnData;
	}

	/**
	 * This function update the user credentials
	 * @name changeLogin
	 * @param void
	 * @return Json data
	 * @access public
	 */
	function changeLogin(){
		# return array data
		$returnData = array();
		# check whether the HTTP Request is an ajax request
		if($this->request->is('ajax')){
			# disable the rendering of the layout
			$this->autoRender = false;
			$this->autoLayout = false;
            
			# Get the data provided
			$loginName = $_POST['username'];
            $first_name = $_POST['first_name'];
            $last_name = $_POST['last_name'];
			$new_pass_1 = $_POST['password_1'];
			$new_pass_2 = $_POST['password_2'];
            $upt_id = $_POST['account_upt_id'];
			$supp_cur_pass = $_POST['old_password'];
			$resetPass = !empty($_POST['reset-pass-check']) ? true: false;

			# Get the user session data
			//$loggedUser = $this->Session->read('userSessionData');
			//$id = $loggedUser['id'];
			# Get the user data from table
			$resultData = $this->User->getUserById($upt_id);
			$old_pass = $resultData['User']['password'];

			if($resetPass){
				#Password Checkings
				$passChk = $this->passwordChecks($new_pass_1, $new_pass_2, $supp_cur_pass, $old_pass);

				if($passChk['code'] == 0){
				   
                    $this->User->id = $upt_id;
            		$data['User'] = array(
						'username' => $loginName ,
                        'first_name' => $first_name,
                        'last_name' => $last_name,
						'password' => md5($new_pass_1),
						'modified_by' => $upt_id,
						'modification_date' =>  date('Y-m-d H:i:s')
					);
            		# save the data
            		$saveStatus = $this->User->save($data);
          
					if($saveStatus){
						$returnData['code'] = 0;
						$returnData['mesg'] ='Account settings saved!';
					}
					else{
						$returnData['code'] = 1;
						$returnData['mesg'] =$this->User->invalidFields();
					}
				}
				else{
					$returnData['code'] = $passChk['code'];
					$returnData['mesg'] = $passChk['mesg'];
				}
			}
			else{
        	    $this->User->id = $upt_id;
        		$data['User'] = array(
					'username' => $loginName ,
                    'first_name' => $first_name,
                    'last_name' => $last_name,
					'modified_by' => $upt_id,
					'modification_date' =>  date('Y-m-d H:i:s')
				);
        		# save the data
        		$saveStatus = $this->User->save($data, true, array('username','first_name','last_name','modified_by','modification_date'));
      
				if($saveStatus){
					$returnData['code'] = 0;
					$returnData['mesg'] ='Account settings saved!';
				}
				else{
					$returnData['code'] = 1;
					$returnData['mesg'] =$this->User->invalidFields();
				}
			}
			echo json_encode($returnData);
		}
	}



}
?>
